﻿#region Using Region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Unisys.InfoImage.IIFCAL;
using Unisys.InfoImage.IIFCAL.IIFClient;
using Unisys.InfoImage.IIFCAL.IIFClient.IIFWorkitem;
using Unisys.InfoImage.IIFCAL.IIFClient.IIFWorkitem.IIFWorkitemInformation;
using Unisys.InfoImage.IIFCAL.IIFClient.IIFQueue;

#endregion

namespace Unisys.InfoImage82.Connection
{
    public class IIFConnection
    {

        #region Global Resources

        public IIFCALMaster CALMaster = new IIFCALMaster();
        public IIFCALClient calClient;
        public IIFCALClientList calClientList;
        public IIFCALQueues calQueues;
        public IIFCALClientListItem calClientListItem;
        public IIFCALClientListItems calClientListItems;
        public IIFCALWorkitemInfo CALWorkitemInfo;
        public bool abortProcessing;

        public int TIMEOUT_MILISECS = 25000;
        public int TIMEOUT_MILISECS_PROCESS = 60000;

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username">InfoImage User</param>
        /// <param name="password">InfoImage user password</param>
        /// <param name="domain">InfoImage Domain</param>
        /// <returns>Returns True if the connection was seccessfull</returns>
        public bool CreateIIFClient(string username, string password, string domain)
        {
            const long OMDCLIENTCREATE_APPLYFUNCSEC = 0x0001;
            const int CALQueueListWorkstep = 128;

            try
            {
                Console.WriteLine("Intentando conectar con usuario" + username);

                if (calClient == null)
                {
                    CALMaster = new IIFCALMaster();
                    calClient = (IIFCALClient)IIFCALMaster.CreateClient(username, password, domain, OMDCLIENTCREATE_APPLYFUNCSEC);
                    calClientList = (IIFCALClientList)calClient.ClientList;
                }
                else
                {
                    Console.WriteLine("Intentando conectar con usuario" + username);
                    IIFCALMaster.Destroy();
                    calClient = (IIFCALClient)IIFCALMaster.CreateClient(username, password, domain, OMDCLIENTCREATE_APPLYFUNCSEC);
                    calClientList = (IIFCALClientList)calClient.ClientList;
                    calQueues = (IIFCALQueues)calClient.GetQueues(CALQueueListWorkstep);


                }
                return true;
            }
            catch (IIFCALException calException)
            {
                Console.WriteLine("Se produjo un problema de conexion Error: " + calException.APIErrorCode + " details: " + calException.Details);
                return false;
            }

        }

        public void DestroyIIFClient()
        {
            try
            {
                if (calClient != null)
                {
                    if (!abortProcessing)
                    {
                        DestroyIIFClientExplicit();
                    }
                }
            }
            catch (IIFCALException calException)
            {
                //ERROR [DestroyIIFClient] CAL Error
            }
        }

        public void DestroyIIFClientExplicit()
        {
            try
            {
                if (calClient == null)
                {
                    //No se encuentran sesiones abiertas para el usuario
                }
                else
                {
                    //Detectamos una sesión abierta para el usuario [..] procediendo a cerrarla..
                    abortProcessing = true;

                    var subThread = new Thread(delegate()
                    {
                        try
                        {
                            calClient.Destroy(IIFDestroyConstants.DestroySaveChanges);
                        }
                        catch (IIFCALException calException)
                        {
                            //ERROR [DestroyIIFClientExplicit::calDestroySaveChanges - Inner Thread] CAL Error " + _gCalError.Code
                        }

                    });

                    subThread.Start();
                    var threadResult = subThread.Join(TIMEOUT_MILISECS);

                    if (threadResult == true)
                    {
                        //Sesión cerrada exitosamente.
                    }
                    else
                    {
                        //Una excepción de timeout ha ocurrido, tratando de cerrar la sesión, proceso abortado. Tratando un nuevo intento descartando cambios.
                    }

                    if (!threadResult)
                    {
                        subThread = new Thread(delegate()
                        {
                            try
                            {
                                calClient.Destroy(IIFDestroyConstants.DestroyAbortChanges);
                            }
                            catch (IIFCALException calException)
                            {
                                //ERROR [DestroyIIFClientExplicit::calDestroyAbortChanges - Inner Thread] CAL Error :
                            }
                        });
                    }
                }
            }
            catch (Exception exception)
            {
            }
        }

        public void ClearIIFClientDesktop()
        {
            try
            {
                if (calClient != null)
                {
                    var subThread = new Thread(delegate()
                    {
                        try
                        {
                            if (!abortProcessing)
                            {
                                calClientList.Clear(IIFClientListClearConstants.ClearSendModWIP);
                            }

                        }
                        catch (IIFCALException calException)
                        {
                            if (!abortProcessing)
                            {
                                //Se produjo un error
                            }
                        }
                    });

                    subThread.Start();
                    var threadResult = subThread.Join(TIMEOUT_MILISECS);

                    if (threadResult == true)
                    {
                        // Escritorio normalizado
                    }
                    else
                    {
                        //Ha ocurrido una excecpcion de timeout urante la normalizacion del escritorio. Proceso abortado.
                    }
                }
            }
            catch (IIFCALException calException)
            {
                //ERROR [ClearIIFClientDesktop] CAL Error 
            }
        }

        public void CheckStatusIIFClientDesktop()
        {
            try
            {

                calClientListItems = (IIFCALClientListItems)calClientList.AllItems;


                foreach (IIFCALClientListItem listItem in calClientListItems)
                {
                    IIFCALWorkitemInfo wii = (IIFCALWorkitemInfo)listItem.Info;
                    if (wii.Status == IIFObjStatusConstants.ObjStatusWIP)
                    {
                        listItem.SendToDefault(IIFSendConstants.SendDiscard);
                    }
                }
            }
            catch (IIFCALException exc)
            {
                // exc.APIErrorCode 



            }
        }

    }
}
